import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {Stock, StockService} from "../stock.service";

@Component({
  selector: 'app-stock-form',
  templateUrl: './stock-form.component.html',
  styleUrls: ['./stock-form.component.css']
})
export class StockFormComponent implements OnInit {

  formModel: FormGroup;
  stock: Stock = new Stock(0, "", 0, 0, "", []);
  categories = ["IT", "互联网", "金融"];

  constructor(private routeInfo: ActivatedRoute, private stockService: StockService, private router: Router) {

  }

  ngOnInit() {
    let stockId = this.routeInfo.snapshot.params['id'];

    let fb = new FormBuilder();
    this.formModel = fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      price: ['', Validators.required],
      desc: [''],
      categories: fb.array([
        new FormControl(false),
        new FormControl(false),
        new FormControl(false)
      ], this.categoriesSelectValidator)
    });

    this.stock = this.stockService.getStock(stockId);
  }

  categoriesSelectValidator(control: FormArray) {
    var valid = false;
    control.controls.forEach(control => {
      if (control.value) {
        valid = true;
      }
    })

    if (valid) {
      return null;
    } else {
      return {categoriesLength: true};
    }
  }

  save() {
    console.log(this.stock.rating);
  }

  cancel() {
    this.router.navigateByUrl('/stock');
  }
}
